<?php

namespace App\Http\Controllers\Wxapi\newWork;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class WorkListController extends CommonController
{
    private $workReplyTableName = "new_work_reply";
    private $workListTableName = "new_work_list";
    private $catTableName = "new_work_cat";
    private $adminUserTableName = "admin_users";
    private $memberTableName = "member";
    private $typeTableName = "new_work_type";
    private $payRecordTableName = "new_work_pay_record";
    private $replyField = [
        "list_id" => "require", "feedback" => "require", "picture" => NULL,
        "annex" => NULL
    ]; // 填入数据库需要存储的表字段;
    private $replyFieldMsg = [
        "list_id" => "所属工单ID", "user_id" => "回复人ID", "feedback" => "反馈内容", "picture" => '图片列表',
        "annex" => "附件列表"
    ];
    public function __construct()
    {
        parent::__construct();
    }

    // 获取工单反馈列表
    public function getWorkList(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $param = request()->post();
        $pageNo = isset($param["pageNo"]) ? $param["pageNo"] : 1;
        $pageSize = isset($param["pageSize"]) ? $param["pageSize"] : 10;
        $data = DB::table($this->workListTableName . " as l")
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','t.cat_id')
            ->where("l.user_id", $this->user["id"])
            ->select("l.id", "l.feedback", "l.status", "l.tag", "l.create_time", "c.name as catName", "t.name as typeName")
            ->skip(($pageNo-1) * $pageSize)->take($pageSize)
            ->orderBy("l.create_time", "desc")
            ->where("l.mall_id", request()->mallData["id"])
            ->get();
        $data = $this->transferFields(json_decode(json_encode($data),true));
        foreach ($data as &$item){
            $item["feedback"] = json_decode($item["feedback"], true);
        }
        $this->result['data'] = $data;
        return $this->return_result($this->result);
    }

    // 获取工单详情
    public function getWorkOrderInfo(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $param = request()->post();
        if(empty($param["id"])){
            $this->result['status'] = 1;
            $this->result['msg'] = '工单ID不能为空';
            return $this->return_result($this->result);
        }
        $data = DB::table($this->workListTableName)->where("id", $param["id"])->first();
        $data = $this->transferFields(json_decode(json_encode($data),true));
        $data["feedback"] = json_decode($data["feedback"], true);
        // 反馈记录
        $replyData = DB::table($this->workReplyTableName)
            ->select("feedback", "picture", "annex", "create_time", "user_id", "submit_id")
            ->orderBy("create_time", "desc")
            ->where("list_id", $param["id"])->get();
        $replyData = $this->transferFields(json_decode(json_encode($replyData),true));
        foreach ($replyData as &$item){
            $item["annex"] = @json_decode($item["annex"]);
            $item["picture"] = explode(",", $item["picture"]);
            if(!empty($item["userId"])){
                if(!isset($temp["admin"][$item["userId"]])){
                    $tmp = DB::table($this->adminUserTableName)->where("id", $item["userId"])->select("name")->first();
                    $temp["admin"][$item["userId"]] = !empty($tmp->name) ? $tmp->name : "";
                }
                $item["isManage"] = "1";
                $item["name"] = $temp["admin"][$item["userId"]];
            }elseif(!empty($item["submitId"])){
                if(!isset($temp["member"][$item["submitId"]])){
                    $tmp = DB::table($this->memberTableName)->where("id", $item["submitId"])->select("name")->first();
                    $temp["member"][$item["submitId"]] = !empty($tmp->name) ? $tmp->name : "";
                }
                $item["isManage"] = "0";
                $item["name"] = $temp["member"][$item["submitId"]];
            }
        }
        $data["replyData"] = $replyData;
        $this->result['data'] = $data;
        return $this->return_result($this->result);
    }

    public function judge($data){
        $annex = @json_decode($data["annex"], true);
        if(empty($annex)){
            return [];
        }
        foreach ($annex as &$item){
            if(isset($item["url"]) && isset($item["cost"]) && $item["cost"] > 0) {
                $record = DB::table($this->payRecordTableName)
                    ->where("key", md5($data["id"] . $item["url"]))
                    ->where("user_id", $this->user["id"])->where("status", "1")->count();
                $item["isPay"] = $record ? "0" : "1";
            }else{
                $item["isPay"] = "0";
            }
        }
        return $annex;
    }

    // 保存工单反馈信息
    public function saveFeedBack(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $params = request()->post();
        foreach ($this->replyField as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !isset($params[$ks])){
                $this->result['status'] = 1;
                $this->result['msg'] = "{$this->replyFieldMsg[$k]}不能为空";
                return $this->return_result($this->result);
            }
            $data[$k] = isset($params[$ks]) ? trim($params[$ks]) : $v;
        }
        $listData = DB::table($this->workListTableName)->select("status")->where("id", $params["listId"])->first();
        if(empty($listData)){
            $this->result['status'] = 1;
            $this->result['msg'] = '工单不存在';
            return $this->return_result($this->result);
        }
        if($listData->status == '3'){
            $this->result['status'] = 1;
            $this->result['msg'] = '工单已解决了';
            return $this->return_result($this->result);
        }
        $data["create_time"] = date("Y-m-d H:i:s");
        $data["submit_id"] = $this->user["id"];
        $res = DB::table($this->workReplyTableName)->insert($data);
        if(!$res){
            $this->result['status'] = 1;
            $this->result['msg'] = '提交失败';
            return $this->return_result($this->result);
        }
        $this->result['msg'] = '提交成功';
        return $this->return_result($this->result);
    }

    public function updateWorkOrderStatus(){
        if ($this->result['status'] > 0){
            return $this->return_result($this->result);
        }
        $param = request()->post();
        if(empty($param["id"])){
            $this->result['status'] = 1;
            $this->result['msg'] = '工单ID不能为空';
            return $this->return_result($this->result);
        }
        if(DB::table($this->workListTableName)->where("id", $param["id"])->update(["status" => 3])){
            $this->result['msg'] = '更新成功';
        }else{
            $this->result['status'] = 1;
            $this->result['msg'] = '更新失败';
        }
        return $this->return_result($this->result);
    }
}
